﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using IHISCETeim.Library;
using IHISCETeim.Model;
using IHISCETeim.DAL;
using System.Data;
using System.Threading;

namespace IHISCETeim.BLL
{
    public enum LoginState
    {
        /// <summary>
        /// 登陆成功
        /// </summary>
        success,
        /// <summary>
        /// 用户名或密码错误
        /// </summary>
        inputerror,
        /// <summary>
        /// 登陆失败
        /// </summary>
        other
    }

    public class OUserController:BaseController
    {
        #region 登陆相关
        public static LoginState Login(string UserName, string Pwd,string loginIP,ref int UserType)
        {
            bool CreatePersistentCookie = true;
            int UserId = 0;
            //核对用户名密码
            LoginState result = IsAuthenticated(UserName, Pwd, loginIP,ref UserId, ref UserType);

            if (result != LoginState.success)
            {
                return result;
            }
            //处理缓存
           
            #region 2014-05-08 之前的登陆COOK 代码
            //FormsAuthentication.SetAuthCookie(UserId.ToString(), CreatePersistentCookie);
                      

            // FormsAuthentication.

           //int PersistentCookieTimeout = 3600 * 24 * 60;
           //// int PersistentCookieTimeout = 60;
           // if (CreatePersistentCookie == true)
           // {
               //FormsAuthenticationTicket AuthenticationTicket = new FormsAuthenticationTicket(UserId.ToString(), true, PersistentCookieTimeout);

           //     string EncryptedAuthTicket = FormsAuthentication.Encrypt(AuthenticationTicket);

           //     HttpCookie AuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedAuthTicket);

           //     AuthCookie.Expires = AuthenticationTicket.Expiration;

           //     AuthCookie.Domain = FormsAuthentication.CookieDomain;

           //     AuthCookie.Path = FormsAuthentication.FormsCookiePath;

           //     HttpContext.Current.Response.Cookies.Set(AuthCookie);
            // }

            bool isPersistent = true;
            DateTime expiration = DateTime.Now.AddMinutes(120);
            CreateFormsAuthenticationTicket(UserId.ToString(), "", isPersistent, expiration);

            #endregion
            //CurrentUser = GetById(UserId);
            
            return LoginState.success;
        }

        /// <summary>
        /// 创建表单验证的票证并存储在客户端Cookie中
        /// </summary>
        /// <param name="userName">当前登录用户名</param>
        /// <param name="roleIDs">当前登录用户的角色ID列表</param>
        /// <param name="isPersistent">是否跨浏览器会话保存票证</param>
        /// <param name="expiration">过期时间</param>
        protected static void CreateFormsAuthenticationTicket(string userName, string roleIDs, bool isPersistent, DateTime expiration)
        {
            // 创建Forms身份验证票据
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                userName,                       // 与票证关联的用户名
                DateTime.Now,                   // 票证发出时间
                expiration,                     // 票证过期时间
                isPersistent,                   // 如果票证将存储在持久性 Cookie 中（跨浏览器会话保存），则为 true；否则为 false。
                roleIDs                         // 存储在票证中的用户特定的数据
             );

            // 对Forms身份验证票据进行加密，然后保存到客户端Cookie中
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            cookie.HttpOnly = true;
            // 1. 关闭浏览器即删除（Session Cookie）：DateTime.MinValue
            // 2. 指定时间后删除：大于 DateTime.Now 的某个值
            // 3. 删除Cookie：小于 DateTime.Now 的某个值
            if (isPersistent)
            {
                cookie.Expires = expiration;
            }
            else
            {
                cookie.Expires = DateTime.MinValue;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 验证用户名及密码，根据数据库
        /// </summary>
        /// <param name="userName">用户帐号</param>
        /// <param name="password">用户登陆密码</param>
        /// <param name="loginIP">用户当前登陆IP</param>
        /// <returns></returns>
        private static LoginState IsAuthenticated(string userName, string pwd, string loginIP,ref int UserId,ref int UserType)
        {
            try
            {
                OUserInfo objNews = CBO.FillObject<OUserInfo>(OUserDAL.UserLogin(userName, StringHelper.GetPwdEncrypt(pwd), loginIP));
                if (objNews!=null)
                {
                    UserId = objNews.UserId;
                    UserType =objNews.UserType;
                    DC.Remove(GetDataCacheKey(LoginOUserInfo, objNews.UserId));
                }
               // UserId = objNews.UserId;
                if (objNews == null)
                {
                    return LoginState.inputerror;
                }
                else if (objNews.State ==0)
                {
                    return LoginState.other;
                }
                else
                {
                    return LoginState.success;
                }
                
            }
            catch
            {
               // UserId = 0;
                return LoginState.other;
            }
            finally
            {
                
            }
        }
       // private static OUserInfo _CurrentUser = null;
        /// <summary>
        /// 获取或设置当前使用用户
        /// </summary>
        public static OUserInfo CurrentUser
        {
            get
            {
                OUserInfo _CurrentUser = null;
                try
                {                        
                        int UserId = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
                        _CurrentUser = DC.Get<OUserInfo>(GetDataCacheKey(LoginOUserInfo, UserId));
                        if (_CurrentUser == null)
                        {
                            _CurrentUser = GetById(UserId);
                            DC.Add(GetDataCacheKey(LoginOUserInfo, UserId), _CurrentUser);
                        }
                    
                    return _CurrentUser;
                }
                catch
                {
                    return new OUserInfo();
                }
            }
            set
            {
                //处理缓存
                DC.Remove(GetDataCacheKey(LoginOUserInfo,value.UserId));
                DC.Add(GetDataCacheKey(LoginOUserInfo, value.UserId), value);
                //_CurrentUser = value;
            }
        }
        /// <summary>
        /// 退出系统
        /// </summary>
        /// <returns></returns>
        public static bool LoginOut()
        {
            DC.Remove(GetDataCacheKey(LoginOUserInfo, CurrentUser.UserId));
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session.Abandon();
            //System.Web.HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            return true;
        }
        #endregion

        public static bool Add(OUserInfo obj)
        {
            obj.PassWord = StringHelper.GetPwdEncrypt(obj.PassWord);
            return OUserDAL.Add(obj);
        }
        public static bool CheckUserName(string UserName)
        {
            return OUserDAL.CheckUserName(UserName);
        }
        public static bool Delete(int UserId)
        {
            return OUserDAL.Delete(UserId);
        }
        public static OUserInfo GetById(int UserId)
        {
            return CBO.FillObject<OUserInfo>( OUserDAL.GetById(UserId));
        }
        public static OUserInfo GetByUserName(string UserName)
        {
            OUserInfo obj= CBO.FillObject<OUserInfo>(OUserDAL.GetByUserName(UserName));
            if (obj == null)
                return new OUserInfo();
            return obj;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="RealName"></param>
        /// <param name="RoleId">角色ID</param>
        /// <param name="UserType"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Sort"></param>
        /// <param name="TotalCount"></param>
        /// <returns></returns>
        public static DataTable GetPagination(string RealName, string RoleId, int UserType, int PageIndex, int PageSize, string Sort, ref int TotalCount)
        {
            return OUserDAL.GetPagination(RealName,RoleId, UserType, PageIndex, PageSize, Sort, ref  TotalCount);
        }

        public static bool Update(OUserInfo obj)
        {
            return OUserDAL.Update(obj);
        }
          /// <summary>
        /// 用户登陆后更改密码或给用户重置密码
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="PassWord"></param>
        /// <returns></returns>
        public static bool EditPwd(int UserId, string PassWord)
        {
            return OUserDAL.EditPwd(UserId, PassWord);
        }

        /// <summary>
        /// 更改用户状态
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="State">0表示启用,1表示禁用</param>
        /// <returns></returns>
        public static bool ChangeState(int UserId, int State)
        {
            return OUserDAL.ChangeState(UserId, State);
        }

        public static void UpdateLastLogin(int UserId, string lastIp)
        {
            OUserDAL.UpdateLastLogin(UserId, lastIp);
        }

         /// <summary>
        /// 更新个性化设置
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="MySetting"></param>
        /// <returns></returns>
        public static bool ChangeMySetting(int UserId, string MySetting)
        {
            DC.Remove(GetDataCacheKey(LoginOUserInfo, UserId));
            return OUserDAL.ChangeMySetting(UserId, MySetting);
        }


        /// <summary>
        /// 根据部门获取部门下所有的员工，只获取状态为可用的员工.@Department 格式为 '''营业一部'',''风险部'''
        /// </summary>
        /// <param name="Departments"></param>
        /// <returns></returns>
        public static DataTable GetUserByDepartment(string Departments)
        {
            return OUserDAL.GetUserByDepartment(Departments);
        }

        #region 一个帐号对应多个公司名,主要用于经销商名称变更
        public static int OUserMutlCmp_Add(int UserId, string AgentName, string Remark)
        {
            return OUserDAL.OUserMutlCmp_Add(UserId, AgentName, Remark);
        }
        public static bool OUserMutlCmp_Delete(int ID)
        {
            return OUserDAL.OUserMutlCmp_Delete(ID);
        }
        public static DataTable OUserMutlCmp_GetListByUserId(int UserId)
        {
            return OUserDAL.OUserMutlCmp_GetListByUserId(UserId);
        }
        public static bool OUserMutlCmp_Update(int ID, string AgentName, string Remark)
        {
            return OUserDAL.OUserMutlCmp_Update(ID, AgentName, Remark);
        }
        /// <summary>
        /// 根据UserId获取多公司名称字符串,格式为"  ('a','b')"
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public static string MutlCmpStr(int UserId)
        {
            DataTable dt = OUserMutlCmp_GetListByUserId(UserId);
            OUserInfo obj=GetById(UserId);
            StringBuilder sb=new StringBuilder();
            sb.Append("  (");
            sb.AppendFormat("'{0}'", obj.Department);
           
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {                   
                    sb.AppendFormat(",'{0}'", dr["AgentName"].ToString().Trim());                   
                }
            }
            sb.Append(")");
            return sb.ToString();
        }

        #endregion
    }
}

